<!--
 * @Description: 新增/编辑用户
 * @Author: chenju
 * @Date: 2022-03-22 17:08:41
 * @LastEditors: chenju
 * @LastEditTime: 2023-02-02 15:56:24
-->
<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    :loading="loading"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <div class="user-dialog-main">
      <!-- <CAlert
        subtitle="账号密码将通过邮件和短信发送给用户，请确保邮箱和手机号输入正确"
        type="info"
      ></CAlert> -->
      <el-form
        ref="formRef"
        class="user-dialog-form"
        :model="taskForm"
        :rules="rules"
        label-position="top"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="realName">
              <el-input v-model.trim="taskForm.realName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录邮箱" prop="username">
              <el-input
                v-model.trim="taskForm.username"
                :disabled="title == '编辑用户'"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" v-if="title == '编辑用户' && !editPhone" required>
              <el-input
                v-model.trim="taskForm.phone"
                placeholder="请输入"
                maxlength="11"
                disabled
              />
              <el-button class="edit-btn" text type="primary" @click="handleEditPhone"
                >编辑</el-button
              >
            </el-form-item>
            <el-form-item label="手机号" prop="phone" v-else>
              <el-input v-model.trim="taskForm.phone" placeholder="请输入" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="employeeNo">
              <el-input v-model.trim="taskForm.employeeNo" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组织归属" prop="organizationIds">
              <el-tree-select
                v-model="taskForm.organizationIds"
                :data="treeData"
                multiple
                collapse-tags
                collapse-tags-tooltip
                show-checkbox
                check-strictly
                filterable
                default-expand-all
                :props="treeProps"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户角色" prop="roleCode" style="margin-bottom: 0">
              <el-checkbox-group v-model="taskForm.roleCode">
                <el-checkbox
                  v-for="(item, index) in enterpriseRoleList"
                  :key="index"
                  :label="item.roleCode"
                >
                  {{ item.roleName }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </CDialog>
</template>
<script lang="ts">
export default {
  name: 'AddOrEditTaskDialog'
};
</script>
<script lang="ts" setup>
import { defineProps, withDefaults, defineEmits, computed, Ref, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { createUser, getUserTreeList, modifyUser } from '@/apis/system/user';
import type {
  GetAuthTreeListTreeItem,
  GetUsersListResultModel,
  GetAuthTreeListResultModel
} from '@/apis/system/model/userModel';
import { store } from '@/store';
import { useUserBusinessRole } from './useUserBusinessRole';
import { transformObjectToKeyList } from '@/utils';
import { CAlert } from '@/components/CAlert';

interface SelectFillTypeDialogProps {
  visible: boolean;
  info: undefined | GetUsersListResultModel[0];
}

const props = withDefaults(defineProps<SelectFillTypeDialogProps>(), {});
const emit = defineEmits(['update:visible', 'refresh']);
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit('update:visible', val);
  }
});
const title = computed(() => {
  if (props.info) {
    return '编辑用户';
  } else {
    return '新增用户';
  }
});
const loading = ref(false);
const editPhone = ref(false);
const { createMessage } = useMessage();
const handleEditPhone = () => {
  editPhone.value = true;
  taskForm.phone = '';
};
const taskForm = reactive({
  realName: '',
  username: '',
  phone: '',
  employeeNo: '',
  organizationIds: [] as number[],
  userId: '',
  id: '',
  roleCode: [] as string[]
});
const { enterpriseRoleList, getRoleList } = useUserBusinessRole();
const formRef = ref();
const treeProps = {
  label: 'organizationName',
  disabled: (data: GetAuthTreeListTreeItem) => {
    return props.info ? !enableUserList.value.includes(data.id) : !data.enable;
  }
};
const treeData = ref<GetAuthTreeListTreeItem[]>([]);
const enableUserList = ref<number[]>([]);
const checkedKeys = ref<number[]>([]);

watch(
  () => dialogVisible.value,
  visible => {
    if (visible) {
      init();
    } else {
      formRef.value?.resetFields();
      initForm();
    }
  }
);
// 初始化
async function init() {
  if (props.info) {
    editPhone.value = false;
    taskForm.userId = String(props.info.userId);
    taskForm.realName = props.info.realName;
    taskForm.username = props.info.username;
    taskForm.phone = props.info.phone;
    taskForm.employeeNo = props.info.employeeNo;

    // 当前成员拥有的角色
    const roles = transformObjectToKeyList(props.info.role);
    // 获取当前登录用户可选角色
    getRoleList().then(res => {
      if (res) {
        taskForm.roleCode = roles;
      }
    });
    loading.value = true;
    try {
      // 获取当前登录用户可选组织
      await getLoginUserTree();
      // 获取当前选中用户已选中组织
      await getUserTree();
    } finally {
      loading.value = false;
    }
  } else {
    // 获取当前登录用户可选角色
    getRoleList();
    getTree();
  }
}
// 初始化表单
function initForm() {
  taskForm.realName = '';
  taskForm.username = '';
  taskForm.phone = '';
  taskForm.employeeNo = '';
  taskForm.roleCode = [];
  taskForm.organizationIds = [];
  enableUserList.value = [];
  checkedKeys.value = [];
}
// 新增时 获取登录用户组织树
function getTree() {
  checkedKeys.value = [];
  const userId = store.state.user.userInfo.userId;
  getUserTreeList({ userId }).then(res => {
    treeData.value = getRealTree(res);
  });
}
// 编辑时 选中用户的组织树
function getUserTree() {
  checkedKeys.value = [];
  const userId = props?.info?.userId;
  getUserTreeList({ userId }).then(res => {
    if (res.length) {
      treeData.value = getRealTree(res);
      taskForm.organizationIds = checkedKeys.value;
    }
  });
}
// 编辑时 当前登录用户可以操作的组织
function getLoginUserTree() {
  const userId = store.state.user.userInfo.userId;
  getUserTreeList({ userId }).then(res => {
    enableUserList.value = [];
    getEnableId(res, enableUserList);
  });
}
// 编辑时 获取编辑时当前登录用户可操作的组织
function getEnableId(data: GetAuthTreeListTreeItem[] | null, list: Ref<number[]>) {
  if (data && data.length) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].enable) {
        list.value.push(data[i].id);
        getEnableId(data[i].children, list);
      } else {
        getEnableId(data[i].children, list);
      }
    }
  }
}

function getRealTree(treeData: GetAuthTreeListResultModel) {
  if (!treeData?.length) return [];
  for (let i = 0; i < treeData.length; i++) {
    const item = treeData[i];
    Object.assign(item, {
      value: item.id
    });
    if (item.belong) {
      checkedKeys.value.push(item.id);
    }
    if (item.children?.length) {
      getRealTree(item.children);
    }
  }
  return treeData;
}

// 提交
function handleConfirm() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      const params: any = {
        realName: taskForm.realName,
        username: taskForm.username,
        organizationIds: taskForm.organizationIds,
        roleCode: taskForm.roleCode,
        employeeNo: taskForm.employeeNo
      };
      if (props.info) {
        Object.assign(params, {
          userId: props.info.userId,
          phone: editPhone.value ? taskForm.phone : null
        });
        modifyUser(params)
          .then(() => {
            createMessage.success('编辑用户成功');
            dialogVisible.value = false;
            emit('refresh');
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        Object.assign(params, {
          phone: taskForm.phone
        });
        createUser(params)
          .then(() => {
            createMessage.success('新增用户成功');
            dialogVisible.value = false;
            formRef.value?.resetFields();
            emit('refresh');
          })
          .finally(() => {
            loading.value = false;
          });
      }
    }
  });
}
</script>
<style lang="scss" scoped>
.user-dialog-main {
  .user-dialog-form {
    margin-top: 16px;
  }
}

.edit-btn {
  position: absolute;
  right: 0;
  top: -30px;
}
</style>
